package com.example.airport;

import androidx.annotation.NonNull;


import android.content.Intent;

import android.os.Bundle;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import android.widget.TextView;
import android.widget.Toast;


import com.example.airport.data.Air;
import com.example.airport.data.Answer;
import com.example.airport.data.Book;

import com.example.airport.data.Directionary;
import com.example.airport.data.Model;
import com.example.airport.data.Suggestion;
import com.example.airport.net.G;

import com.example.airport.parent.MainFatherActivity;

import com.example.airport.service.MyService;
import com.example.airport.utils.DictUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;
import com.shawnlin.preferencesmanager.PreferencesManager;
import java.io.IOException;
import java.sql.SQLOutput;
import java.util.ArrayList;

import butterknife.BindView;
import okhttp3.ResponseBody;

public class MainActivity extends MainFatherActivity {

    @BindView(R.id.empty_text)
    TextView empty_text;
    int count=0;  //堆栈中的数据长度
    int current_type=0;   //0-飞行员 1-管制员
    String current_text=""; //当前人员准备说的话
    int model=0;  //当前模式: 0：ai 模式  1：人工模式  在ConfigActivity中会用到


    /**
     * 播放语音
     * @param text
     */
    void broadVoise(String text)
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int code = mTts.startSpeaking(text, mTtsListener);
            }
        }).start();

    }


    /***
     * 播放回调
     */
    protected SynthesizerListener mTtsListener = new SynthesizerListener() {
        //开始播放

        @Override
        public void onSpeakBegin() {
            System.out.println("====开始播放==");
        }

        //暂停播放

        @Override
        public void onSpeakPaused() {
        }

        //继续播放

        @Override
        public void onSpeakResumed() {
        }

//合成进度

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
        }

        //播放进度

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

    //播放完成

        @Override

        public void onCompleted(SpeechError error) {
            if(current_type==0)
            {
                getCraftData(current_text,"");
            }
        }

    //事件
        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        }

    };


    /***
     * 如果收到的飞行员的信息
     * @param text
     */
    void onPilotData(Air air,String text)
    {

        //System.out.println("===获取飞行员说话==");
        //System.out.println("==当前模式:" +this.model);
        String _reporter=(air.getData().getReporter()==null)?G.PILOT_INIT:air.getData().getReporter();
        this.current_type=0; //当前准备说话的是飞行员
        this.current_text=text; //当前准备说的话
        addItem(_reporter,text,0);

        //System.out.println("获取是否允许播报:" + PreferencesManager.getBoolean("pilot",G.PILOT));

        if(PreferencesManager.getBoolean("pilot",G.PILOT)) broadVoise(text); //播报语音
        else
        {
            switch (this.model)
            {
                case 0: //发送数据到语义
                    getCraftData(text,"");
                    break;
                case 1: //向人工席发布
                    publish_agent_text(text);
                    break;
            }
        }

    }

    /***
     * 如果收到的是特殊指令
     * @param text
     */
    void onOrderData(String text)
    {
        String[] split = text.split("&");
        String _name=G.NOREPORTER;
        String _broadcast="";
        String _text=G.NOMATCH;

        if(split.length==3)
        {
            _name=split[0];
            _broadcast=split[1];
            _text=split[2];
        }else if(split.length==2)
        {

            _broadcast=split[0];
            _text=split[1];
        }else
        {
            _broadcast=split[0];
            _text=split[0];
        }
        addItem(_name,_text,3);
        publish_msg(_broadcast);
        this.current_type=1;//当前准备说话的是管制人员
        if(PreferencesManager.getBoolean("craft",G.CRAFT)) broadVoise(_broadcast); //播报语音

    }


   /**
    * 数据解析后，写在UI里
    * */
    void addItem(String _reporter,String _text,int type)
    {
        count++;
        if(count>0) empty_text.setVisibility(View.GONE);
        Book book=new Book(_reporter,_text,type);
        fixList.push(book);
        adapter.bindData(fixList);
        recyclerView.setAdapter(adapter);
        recyclerView.scrollToPosition(fixList.size() - 1);
    }

    /**
     * 清理列表
     * */
    void clearItem()
    {
        count=0;
        empty_text.setVisibility(View.VISIBLE);
        fixList.clear();
        adapter.bindData(fixList);
        recyclerView.setAdapter(adapter);

    }


    /**
     * MQTT获取结果，即：从飞行员，或特殊指令
     * */

    @Override
    public void onSubscribedData(int type,String topic,String msg) {
        super.onSubscribedData(type,topic,msg);
       // System.out.println("===Topic:"+ topic);
        runOnUiThread(() -> {
            switch (type)
            {
                case 0:
                    onSubscribeType(topic,msg);
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                    break;
            }

        });

    }

    //根据订阅到的主题进行分类处理
    void onSubscribeType(String topic,String msg)
    {

        switch (topic)
        {
            case G.TOPIC_PILOT:
                onAnalysisData(msg);
                break;
            case G.TOPIC_AITRAIN_CHANGE_MODEL:  //订阅模式改变命令
                onSubscribeChangeModel(msg);

                break;
            case G.TOPIC_AITRAIN_ANSWER: //订阅理解后的回答
                onAItrainAnswer(msg);
                break;
            case G.TOPIC_AITRAIN_GET_MODEL:  //订阅获取当前模式
                publish_model(this.model);//将获取到的模式，发布出去
                break;
        }
    }

    /***
     *订阅理解后的应答
     *
     */

    void onAItrainAnswer(String msg)
    {
        Gson gson = new Gson();
        Answer answer = gson.fromJson(msg, Answer.class);
        Answer.Data data=answer.getData();
        onOrderData(data.getText());

    }

    /***
     *订阅改变模式
     * 0：ai 模式  1：人工模式
     */

    void onSubscribeChangeModel(String msg)
    {
        Gson gson = new Gson();
        Model model = gson.fromJson(msg, Model.class);
        Model.Data data=model.getData();
        this.model=data.model;
        publish_model(this.model);//将获取到的模式，发布出去
    }

    /**
     *
     * 收到数据,在列表中显示出来
     */
    void onAnalysisData(String msg)
    {

        if(msg.isEmpty()) return;
        Air air=dataAdapter(msg);
        if(air==null) return;
        if(air.getData()==null) return;

        String text=air.getData().getText();
        if(air.getMsg_type().equals(G.MSG_TYPE))
        {
            onPilotData(air,text);
        }
        else
        {
            onOrderData(text);
        }


    }




    /**
     * 清理缓存
     */
    void clearStorage()
    {
        getCraftData("","clear");
        clearItem();
        Toast.makeText(getApplicationContext(), "清理成功！", Toast.LENGTH_SHORT).show();

    }
    /**菜单的点击事件*/
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.setting:

                Intent intent = new Intent();
                intent.putExtra("model",this.model);
                intent.setClass(MainActivity.this, ConfigActivity.class);
                startActivity(intent);
                break;
            case R.id.reback:
                restoreSetting("您确定要恢复配置吗?");
                break;

            case R.id.clear:
                clearStorage();
                break;

            case R.id.reConnect:
                toDisConnect();
                toConnect();
                break;
            case R.id.quite:

                leaveSystem("您确定要关闭程序吗?", false);
                break;
            default:
                super.onOptionsItemSelected(item);
        }
        return true;
    }

    /**
     * http获取结果，即：从语义处得到结果
     * */
    @Override
    public void success(int index, ResponseBody body) throws IOException {
        java.lang.reflect.Type type = new TypeToken<Suggestion>() {}.getType();
        String json = new String(body.bytes());

        Gson gson = new Gson();
        Suggestion suggestion = gson.fromJson(json, type);


        if(suggestion.getData().getAppmsg()!=null && suggestion.getData().getAppmsg().equals("clear")) return;

        Suggestion.Data.Curdata curdata=suggestion.getData().getCurdata();

        String backText=PreferencesManager.getString("nomatch",G.NOMATCH);
        String reporter=G.NOREPORTER;

        if( curdata !=null)
        {
            String answer=curdata.getAnswer();
            String[] split = answer.split("&");
            backText=split[1];
            reporter=split[0];

            if (curdata.getAction().equals("clear")) getCraftData("","clear");  //如果收到的字符串有 clear,则发送一次清理

        }

        this.current_type=1;  //当前准备说话的是管制人员
        addItem(reporter,backText,1);  //写回界面


        if(PreferencesManager.getBoolean("craft",G.CRAFT)) broadVoise(backText); //播报语音

        publish_msg(backText);
    }

    @Override
    public void failure(int index, String msg) {
        System.out.println("====返回失败"+msg);
    }



    void publish_msg(String text)
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long timestamp = System.currentTimeMillis();//生成时间戳
                String pub_msg="{\"msg_type\": \"tts\",\"time\": "+ timestamp +",\"data\": {\"text\": \""+ text +"\"}}";
                myService.toPublish(G.TOPIC_AIRCRAFT,pub_msg);
            }
        }).start();
    }

    /***
     * 发布当前模式
     * @param model
     */
    void publish_model(int model)
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long timestamp = System.currentTimeMillis();//生成时间戳
                String pub_msg="{\"msg_type\": \"tts\",\"data\": {\"model\": "+ model +"}}";
                myService.toPublish(G.TOPIC_AGENT_CHANGE_MODEL,pub_msg);
            }
        }).start();
    }


    /***
     * 发布当前模式
     * @param text
     */
    void publish_agent_text(String text)
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long timestamp = System.currentTimeMillis();//生成时间戳
                String pub_msg="{\"msg_type\": \"tts\",\"data\": {\"text\": \""+ text +"\"}}";
                myService.toPublish(G.TOPIC_AGENT_TEXT,pub_msg);
            }
        }).start();
    }



}